<?php
/**
 * 进销存管理
 * 张名尊，20140504 
 * 1、销量录入
 * 2、销量统计
 */ 


class salesAction extends backendAction{
    
    /**
     * 构造函数
     */ 
    public function _initialize(){
        parent::_initialize();
        $this->_cate_mod = D('region');
    }
    
    public function _before_index(){
        
        //销量录入按钮
        $bigMenu = array(
                'title' =>'销量录入',
                'iframe' => U('sales/oppt',array('opttype'=>'add')),
                'id' => 'add',
                'width' => '500',
                'height' => '400'         
        );
        $this->list_relation = true;
        $brandList = D('brand')->cate_cache();
		//var_dump($brandList);
        $this->assign('brandList',$brandList);
        $this->assign('big_menu',$bigMenu);
    }
    
   protected function _search() {
        $map = array();
        ($time_start = $this->_request('time_start', 'trim')) && $map['createTime'][] = array('egt', strtotime($time_start));
        ($time_end = $this->_request('time_end', 'trim')) && $map['createTime'][] = array('elt', strtotime($time_end)+(24*60*60-1));        
       
        $verify = $this->_request('verify', 'trim');
        if(is_numeric($verify)){ 
            $map['s.verify'] = $verify;
        }
        $channel = $this->_request('channel', 'trim');
        if(is_numeric($channel)){ 
            $map['store.channel'] = $channel;
        }        
        $cate_id = $this->_request('regionId');
        $selected_ids = '';
        if ($cate_id) {
            $regionArr = explode('_',$cate_id);
            if(count($regionArr)==2){
              $regionId = $regionArr[0];
              $storeId   = $regionArr[1];  
              $map['s.storeId']  = $storeId ;
              $spid = $this->_cate_mod->where(array('id'=>$regionId))->getField('spid');
              $selected_ids = $spid ? $spid . $regionId .'|'.$regionId.'_'.$storeId: $regionId.'|'.$regionId.'_'.$storeId;
            }else{
                $id_arr = $this->_cate_mod->get_child_ids($cate_id, true);
                $id_arr = M('store')->where(array('regionId'=>array('in',$id_arr)))->getField('id,name');
                $id_arr = array_keys($id_arr);
                $map['s.storeId'] = array('in',$id_arr);
                $spid = $this->_cate_mod->where(array('id'=>$cate_id))->getField('spid');
                $selected_ids = $spid ? $spid . $cate_id : $cate_id;
            }          
        }
        
        $userName = $this->_request('userName', 'trim');
        if ($userName) {
            
            $where['userName']  = array('like',"%$userName%");
            $where['realName']  = array('like',"%$userName%");
            $where['_logic'] = 'or';
            $userMap['_complex'] = $where;  
            $id_arr = M('admin')->where($userMap)->getField('id,userName');

            $ids = array_keys($id_arr);
            $ids = implode(',',$ids);
            if(!empty($_SESSION[C('user_session_name')]['underListIds'])){
                $ids .=','.$_SESSION[C('user_session_name')]['underListIds'];
                 
            }
            
            $ids = trim($ids,',');
        
            if(empty($ids)){
               $ids = "-1"; 
            }
               
            $map['userId'] = array('in',$ids);
        }
        $admin = getUserSession();
        
        
        if($admin['roleId']==7)
        {
            $map['userId'] = $admin['id'];
        }
		$brandId = $this->_request('brandId', 'intval');
		$modelId = $this->_request('modelId', 'intval');
        
		if(empty($modelId)){
		    if($brandId){
		     // var_dump($brandId);
    			$modelList = M('model')->where(array('brandId'=>$brandId))->getField('id,name');
                //echo M('model')->getLastSql();
    			$modelIds = array_keys($modelList);
    			$map['s.modelId']=array('in',$modelIds);
            }
		}else{
			$map['s.modelId'] = $modelId;
		}		
        $imei = $this->_request('imei','trim');
        if($imei){
            $map['s.imei'] = $imei;
        }
        
        $this->assign('search', array(
            'time_start' => $time_start,
            'time_end' => $time_end,       
            'cate_id' => $cate_id,
            'selected_ids' => $selected_ids,
            'channel'  => $channel,
            'verify'  => $verify,
			'brandId'  => $brandId,
			'modelId'  => $modelId,
            'group'=>$this->_request("group", 'trim'),
            'userName' => $userName,
            'imei'=>$imei,
            
        ));
       //ddd var_dump($map);
        return $map;
    }
    private function readyData(){
        $brandList = F('brand_list');
        $this->assign('brandList',$brandList);
        if($this->_request('opttype','trim')=='add'){
            $info['realName'] = $_SESSION[C('user_session_name')]['realName'];
            $this->assign('info',$info);
        }
        
    }
    
    /**
     * 销量表增改操作
     */ 
    public function oppt(){
        
        $opptType = $this->_request('opttype','trim');
        $this->readyData();
        if(IS_POST){
            $regionId = $this->_request('regionId');
            if(strpos($regionId,'_')){
               list($regionId,$storeId) = explode('_',$regionId); 
               $_POST['storeId'] = intval($storeId);
            }
            $userName = $this->_request('realName','trim');
            if($userName){
                $where['realName'] = $userName;
                $where['userName'] = $userName;
                $where['_logic'] = 'or';
                $userMap['_complex'] = $where;
                $userMap['storeId'] = intval($storeId);
                $userId = M('admin')->where($userMap)->getField('id');
                $_POST['userId'] = intval($userId);
                if(empty($userId)){
                    IS_AJAX && $this->ajaxReturn(0, '找不到用户:'.$userName, '', 'add');
                }
            }
        }
        $this->assign('opptType',$opptType);
        $this->$opptType();
    }
    
    
    
    


    /**
     * 列表处理
     *
     * @param obj $model  实例化后的模型
     * @param array $map  条件数据
     * @param string $sort_by  排序字段
     * @param string $order_by  排序方法
     * @param string $field_list 显示字段
     * @param intval $pagesize 每页数据行数
     */
    protected function _list($model, $map = array(), $sort_by='', $order_by='', $field_list='*', $pagesize=20,$group_by='')
    {
        //排序
        $mod_pk = $model->getPk();
        if ($this->_request("sort", 'trim')) {
            $sort = $this->_request("sort", 'trim');
        } else if (!empty($sort_by)) {
            $sort = $sort_by;
        } else if ($this->sort) {
            $sort = $this->sort;
        } else {
            $sort = $mod_pk;
        }
        if(empty($group) && $sort=='number'){
            $sort = 'id';
        }
        if($sort!='number'){
            $sort = 's.'.$sort;
        }
        if ($this->_request("order", 'trim')) {
            $order = $this->_request("order", 'trim');
        } else if (!empty($order_by)) {
            $order = $order_by;
        } else if ($this->order) {
            $order = $this->order;
        } else {
            $order = 'DESC';
        }
        if ($this->_request("group", 'trim')) {
            $group = $this->_request("group", 'trim');
        } else if (!empty($group_by)) {
            $group = $group_by;
        } else if ($this->group) {
            $group = $this->group;
        }else{
            $group = '';
        }   
        //var_dump($group);
        $optype = $this->_request('opttype','trim','search');
           
        //地区权限
        $fields = $model->getDbFields();
        $admin = getUserSession();
        if(!empty($admin['regionIds'])){
            $map['store.regionId'] = array('in',$admin['regionIds']);
        }
        if(!empty($admin['storeChannel'])){
            $where['store.channel']  = 0;
            $where['store.channel']  = $admin['storeChannel'];  
            $where['_logic'] = 'or';
            $map['_complex'] = $where;
        }
        if(!empty($admin['underListIds'])){
            $map['s.userId'] = array('in',$admin['underListIds']);;
        }
        
        $field_list = array(
            "s.imei"=>'imei',
            "s.id"=>'id',
            "FROM_UNIXTIME(s.createTime)"=>'createTime',
            "s.verify"=>'verify',
            "r.name"=>'regionName',
            'store.regionId'=>'regionId',
            'store.name'=>'storeName',
            'store.ctms'=>'storeCtms',
            'store.channel'=>'channel',
            'm.name'=>'modelName',
            'u.realName'=>'userRealName',
            'city.name'=>'cityName',
            'r.name'=>'regionName',
            'bigcity.name'=>'bigcityName',
            //'1'=>'number',
        );
        if($group){
            $map['s.verify'] = 1;
            $field_list['count(distinct(s.imei))'] = 'number';
        }
        if($optype=='export'){
           $pagesize = 0; 
        }
                    
       //如果需要分页
        if ($pagesize) {
            $count = $model->alias('s')
                    ->join(C('DB_PREFIX')."store AS store ON store.id = s.storeId")
                    ->join(C('DB_PREFIX')."region AS r ON r.id = store.regionId")
                    ->join(C('DB_PREFIX')."region AS city ON r.pid = city.id")
                    ->join(C('DB_PREFIX')."region AS bigcity ON bigcity.id = city.pid")   
                    ->join(C('DB_PREFIX')."admin AS u ON u.id = s.userId")
                    ->join(C('DB_PREFIX')."model AS m ON m.id = s.modelId")
                    ->where($map)->count('s.'.$mod_pk);
            $pager = new Page($count, $pagesize);
        }      
        $select = $model->alias('s')->field($field_list)
                    ->join(C('DB_PREFIX')."store AS store ON store.id = s.storeId")
                    ->join(C('DB_PREFIX')."region AS r ON r.id = store.regionId")
                    ->join(C('DB_PREFIX')."region AS city ON r.pid = city.id")
                    ->join(C('DB_PREFIX')."region AS bigcity ON bigcity.id = city.pid")                    
                    ->join(C('DB_PREFIX')."admin AS u ON u.id = s.userId")
                    ->join(C('DB_PREFIX')."model AS m ON m.id = s.modelId")->where($map)
                    ->order($sort . ' ' . $order)->group($group);     
        if ($pagesize) {
            $select->limit($pager->firstRow.','.$pager->listRows);
            $page = $pager->show();
            $this->assign("page", $page);
        }
        
        

        $list = $select->select();
        //echo $select->getLastSql();
        if($optype=='export'){
            $this->exportExcel($list);
            exit();
        }        
        $this->assign('list', $list);
        $this->assign('list_table', true);
    }   
    
    public function exportExcel($data){
   	    import('@.ORG.Excel.Excel');
        $list[0] = array(
            'id',
            'imei',
            '销售人员',
            '厅店名称',
            '亚信编码',
            '地区名称',
            '机型',
            '销售时间',
            '验证信息',
            '数量'
            
        );
        $verifyArr = array(
            0=>'未验证',
            1=>'验证通过',
            -1=>'验证未通过',
        );
        foreach($data as $k=>$v){
            $temp = array();
            $v['verify'] = $verifyArr[$v['verify']];
            $temp[] = $v['id'];
            $temp[] = $v['imei'];
            $temp[] = $v['userRealName'];
            $temp[] = $v['storeName'];
            $temp[] = $v['storeCtms'];
            $group = $this->_request('group','trim');
            if($group=='bigcity.id'){
                $regionName = $v['bigcityName'];
            }elseif($group=='city.id'){
                $regionName = $v['bigcityName'].'=》'.$v['cityName'];
            }else{
                $regionName = $v['bigcityName'].'=》'.$v['cityName'].'=》'.$v['regionName'];
            }            
            $temp[] = $regionName;
            $temp[] = $v['modelName'];
            $temp[] = $v['createTime'];
            $temp[] = $v['verify'];
            $temp[] = $v['number']>0?$v['number']:1; 
            $list[] = $temp;
        }
		$xls = new Excel( 'UTF-8', false, '销量记录'.Date('Y-m-d') );
		$xls->addArray($list);
		$xls->generateXML($file_name.date( 'YmdHis'));        
        
    }
    
	/**
	 * 工资预估
	 */
	public function pay(){
	   $userInfo = getUserSession();

       $this->assign('userInfo',$userInfo);
       $cityId = $userInfo['cityId'][0];
       if(!is_array($cityId)){
            $this->assign('cityName',M('region')->where(array('id'=>$cityId))->getField('name'));
       }
       
       $wage = D('admin')->wage($userInfo['id']);
      // var_dump($userInfo);
//var_dump($wage);
       $this->assign('wage',$wage);
	   $this->display();
	}
    /**
     * 工资计算
     * 
     */
    public function actPay(){
        $importModel = $this->_get('importModel','intval',0);
        $allModel = $this->_get('allModel','intval',0);
        $modelRate = $this->_get('modelRate','trim',0.2);
        
        $userInfo = getUserSession();
        $userId = $userInfo['id'];
                
        $importTargetNumber = 0;
        $totalTargetNumber = 0;
        foreach(D('target')->userTarget($userId) as $k=>$v){
            if($v['modelId']>0){
                $importModelNumber +=$v['target'];
            }elseif($v['modelId']==-1){
                $totalTargetNumber = $v['target'];
            }
        }
        //var_dump($importModelNumber);
        $salerTarget = $importModel/$importModelNumber;
        $allTarget = $allModel/$totalTargetNumber;
        //写死0.2
        $importentModel = $importModel*$modelRate;
        $wage = D('admin')->computing($userId,$salerTarget,$allTarget,$importentModel);
        $this->ajaxReturn(1,'',$wage['total']);
        
    }
        
     
    
}





?>